package com.zhuanzhuan.service.impl;

import com.zhuanzhuan.dao.GoodsDao;
import com.zhuanzhuan.dao.TradelogDao;
import com.zhuanzhuan.dao.TypeDao;
import com.zhuanzhuan.dao.UserDao;
import com.zhuanzhuan.dao.impl.GoodsDaoMySQLImpl;
import com.zhuanzhuan.dao.impl.TradelogDaoMySQLImpl;
import com.zhuanzhuan.dao.impl.TypeDaoMySQLImpl;
import com.zhuanzhuan.dao.impl.UserDaoMySQLImpl;
import com.zhuanzhuan.entity.Goods;
import com.zhuanzhuan.entity.Tradelog;
import com.zhuanzhuan.entity.Type;
import com.zhuanzhuan.entity.User;
import com.zhuanzhuan.service.UserService;
import com.zhuanzhuan.vo.GoodsDetail;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Scanner;
import java.util.TimeZone;

public class UserServiceImpl implements UserService {
    //上架新的好物
    @Override
    public void addNewGoods(User user) {
        try {
            Scanner input = new Scanner(System.in);
            Goods goods = new Goods();
            System.out.print("请输入好物名称:");
            goods.setName(input.next());
            //创建DAO对象
            TypeDao typeDao = new TypeDaoMySQLImpl();
            List<Type> types = typeDao.getTypeList();
            //构造好物类别提示
            String typeHint = "";
            for (int i = 0; i < types.size(); i++) {
                typeHint += i + 1 + "." + types.get(i).getName();
                if (i != types.size() - 1) {
                    typeHint += ",";
                }
            }
            System.out.print("请输入好物类别(" + typeHint + "):");
            goods.setTypeID(types.get(Integer.valueOf(input.next())).getId());
            System.out.print("请输入好物价格:");
            goods.setPrice(Float.valueOf(input.next()));
            System.out.print("请输入好物介绍:");

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            try {
                //使用readLine()方法读取整行输入
                goods.setDescription(reader.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //获取系统时间
            LocalDateTime today = LocalDateTime.now();
            //将日期格式化为字符串
            goods.setAddTime(Date.from(today.atZone(TimeZone.getTimeZone("GMT+8").toZoneId()).toInstant()));
            goods.setOnSell(true);
            goods.setOwnerID(user.getId());
            //创建DAO对象
            GoodsDao goodsDao = new GoodsDaoMySQLImpl();
            if(goodsDao.addNewGoods(goods) > 0) {
                System.out.println("好物上架成功！");
            }else{
                System.out.println("好物上架失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("输入错误");
        }
    }

    //用户登录
    @Override
    public User login(String name, String pwd) {
        //创建DAO对象
        UserDao userDao = new UserDaoMySQLImpl();
        User user = userDao.getUserByNameAndPwd(name, pwd);
        return user;
    }

    //显示好物信息
    @Override
    public void listGoods(User user, int type) {
        int curPage = 0;
        //创建DAO对象
        GoodsDao goodsDao = new GoodsDaoMySQLImpl();
        Scanner input = new Scanner(System.in);
        boolean isShowGoods = true;
        List<GoodsDetail> listGoods = null;
        do{
            if(isShowGoods) {
                listGoods = goodsDao.listOnSellGoods(curPage,type);
                showListGoods(listGoods, curPage);
            }
            int pageCounts = (int) Math.ceil(goodsDao.getOnSellGoodsCountByType(type) / 5.0);
            //判断当前页是否为最后一页
            boolean hasLastPage = pageCounts > curPage + 1;
            System.out.println("1.查看好物详情\t2.上一页\t3.下一页\t0.返回上一级");
            System.out.print("请输入要执行的操作:");
            String action = input.next();
            //查看
            if (action.equals("1")) {
                System.out.print("请输入要查看的好物编号:");
                int index = Integer.valueOf(input.next()) - curPage*5;
                if (index <= listGoods.size() && index >= 1) {
                    GoodsDetail goods = listGoods.get(index-1);
                    showGoodsDetail(goods);
                    System.out.println("1.购买此好物\t其他输入返回上一级");
                    System.out.print("请输入要执行的操作:");
                    action = input.next();
                    if(action.equals("1")){
                        if(buyGoods(user, goods)){
                            System.out.println("购买成功！");
                        }else{
                            System.out.println("购买失败！");
                        }
                    }
                    break;
                }else{
                    System.out.println("好物编号输入错误！");
                }
            }//显示上一页
            else if (action.equals("2")) {
                //当前页不是首页的情况
                isShowGoods = curPage > 0;
                if (isShowGoods) {
                    curPage--;
                } else {
                    System.out.println("已到首页，无法向前翻页！");
                }
            }//显示下一页
            else if (action.equals("3")) {
                //当前不是尾页的情况
                isShowGoods = hasLastPage;
                if (hasLastPage) {
                    curPage++;
                } else {
                    System.out.println("已到尾页，无法向后翻页！");
                }
            } else if (action.equals("0")) {
                break;
            } else {
                System.out.println("输入错误，请重新输入");
            }
        }while(true);
    }

    private void showListGoods(List<GoodsDetail> listGoods, int curPage){
        System.out.println("编号\t名称\t价格\t上架时间");
        for(int i = 0; i < listGoods.size(); i++){
            GoodsDetail goods = listGoods.get(i);
            int index = curPage*5+i+1;
            System.out.println(index+"\t"+
                    goods.getName()+"\t" +
                    goods.getPrice()+"\t" +
                    goods.getAddTime()+"\t");
        }
    }

    private void showGoodsDetail(GoodsDetail goods){
        System.out.println("好物名称:" + goods.getName());
        System.out.println("好物类型:" + goods.getType());
        System.out.println("好物价格:" + goods.getPrice());
        System.out.println("好物主人:" + goods.getOwner());
        System.out.println("好物介绍:" + goods.getDescription());
        System.out.println("上架时间:" + goods.getAddTime());
    }

    //购买好物
    @Override
    public boolean buyGoods(User buyer, GoodsDetail goods) {
        //判断购买者的余额会否足够买好物
        if(buyer.getBalance() < goods.getPrice()) {
            System.out.println("余额不足，无法购买！");
        }else if(buyer.getId() == goods.getOwnerID()){
            System.out.println("不能购买自己的好物！");
        }else{
            System.out.print("请输入收货信息：");
            //会使用到空格等字符，需要使用BufferedReader读取输入
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            try {
                //使用readLine()方法读取整行输入
                Tradelog tradelog = new Tradelog();
                tradelog.setReceiveInfo(reader.readLine());
                tradelog.setBuyerID(buyer.getId());
                tradelog.setSellerID(goods.getOwnerID());
                tradelog.setGoodsID(goods.getId());
                //获取系统时间作为交易时间
                LocalDateTime today = LocalDateTime.now();
                tradelog.setTradeTime(Date.from(today.atZone(ZoneId.systemDefault()).toInstant()));//获得格式化后的日期+时间字符串
                //创建DAO对象
                TradelogDao tradelogDao = new TradelogDaoMySQLImpl();
                GoodsDao goodsDao = new GoodsDaoMySQLImpl();
                UserDao userDao = new UserDaoMySQLImpl();
                if(tradelogDao.addTradelog(tradelog) > 0
                        && goodsDao.updateGoodsOnSellState(goods.getId(),false)>0
                        &&userDao.addBalance(goods.getOwnerID(), goods.getPrice())>0
                        &&userDao.minusBalance(buyer.getId(), goods.getPrice())>0){
                    return true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //显示指定用户的好物列表
    @Override
    public void listUserGoods(User user){
        int curPage = 0;
        //创建DAO对象
        GoodsDao goodsDao = new GoodsDaoMySQLImpl();
        Scanner input = new Scanner(System.in);
        boolean isShowGoods = true;
        List<GoodsDetail> listGoods = null;
        do{
            if(isShowGoods) {
                listGoods = goodsDao.listOnSellGoodsByUserID(user.getId(),curPage);
                showMyGoods(listGoods, curPage);
            }
            int pageCounts = (int) Math.ceil(goodsDao.getOnSellGoodsCountByUserID(user.getId()) / 5.0);
            //判断当前页是否为最后一页
            boolean hasLastPage = pageCounts > curPage + 1;
            System.out.println("1.上一页\t2.下一页\t0.返回上一级");
            System.out.print("请输入要执行的操作:");
            String action = input.next();
            if (action.equals("1")) {
                //当前页不是首页的情况
                isShowGoods = curPage > 0;
                if (isShowGoods) {
                    curPage--;
                } else {
                    System.out.println("已到首页，无法向前翻页！");
                }
            }//显示下一页
            else if (action.equals("2")) {
                //当前不是尾页的情况
                isShowGoods = hasLastPage;
                if (hasLastPage) {
                    curPage++;
                } else {
                    System.out.println("已到尾页，无法向后翻页！");
                }
            } else if (action.equals("0")) {
                break;
            } else {
                System.out.println("输入错误，请重新输入");
            }
        }while(true);
    }


    private void showMyGoods(List<GoodsDetail> listGoods, int curPage){
        System.out.println("序号\t名称\t类型\t价格\t上架时间\t描述");
        for(int i = 0; i < listGoods.size(); i++){
            GoodsDetail goods = listGoods.get(i);
            int index = curPage*5+i+1;
            System.out.println(index+"\t"+
                    goods.getName()+"\t" +
                    goods.getType()+"\t" +
                    goods.getPrice()+"\t"+
                    goods.getAddTime()+"\t"+
                    goods.getDescription());
        }
    }
}
